package com.define.ssh.action.userconfig;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.StringUtils;

import com.define.ssh.action.admin.BaseAdminAction;
import com.define.ssh.common.JqueryZTreeNode;
import com.define.ssh.common.JsonUtil;
import com.define.ssh.model.Compdept;
import com.define.ssh.model.DeptAccount;
import com.define.ssh.model.Deptuser;
import com.define.ssh.model.UserInfo;
import com.define.ssh.model.UserRoamingdata;
import com.define.ssh.service.CompdeptService;
import com.define.ssh.service.DeptuserService;
import com.define.ssh.service.UserInfoService;
import com.define.ssh.service.UserRoamingdataService;
import com.define.ssh.util.InterfaceIpData;
import com.define.ssh.util.SystemUtil;
import com.sxit.ecwx.core.utils.Formatu;

/***
 * 
 * @author sc
 * 
 */
@ParentPackage("userconfig")
public class UserConfigAction extends BaseAdminAction {

	/** 页面传递参数过来 */
	protected int pageSize;
	protected int pageNum;

	private String node;
	private Integer pid;
	private Integer deptid;

	@Resource(name = "compdeptServiceImpl")
	private CompdeptService compdeptService;

	@Resource(name = "userInfoServiceImpl")
	private UserInfoService userInfoService;

	@Resource(name = "deptuserServiceImpl")
	private DeptuserService deptuserService;

	@Resource(name = "userRoamingdataServiceImpl")
	private UserRoamingdataService userRoamingdataService;

	private String uname;
	private Integer utype;
	private List deptList = new ArrayList();
	private String deptids;

	public String index() {

		/*
		 * DetachedCriteria dt = DetachedCriteria.forClass(Compdept.class);
		 * List<Compdept> wyulist=compdeptService.findByCriteria(dt);
		 * System.out.println("==============="+wyulist.size());
		 */

		/*
		 * HashMap<String, Object> searchMap = new HashMap<String, Object>();
		 * pager.setSearchMap(searchMap); pager =
		 * compdeptService.findPager(pager);
		 */
		
		return "index";
	}

	/***
	 * 加载tree
	 * 
	 * @return
	 */
	public void loadTree() throws Exception {

		try {

			final HttpServletResponse response = ServletActionContext
					.getResponse();
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");

			if (StringUtils.hasText(node)) {

				final List<JqueryZTreeNode> list = compdeptService
						.loadTree(Integer.valueOf(node));
				//list.add(this.getOther());
				response.getWriter().write(JsonUtil.listToJson(list));
			} else {
				final List<JqueryZTreeNode> list = compdeptService.loadTree(0);
				//list.add(this.getOther());
				response.getWriter().write(JsonUtil.listToJson(list));
			}
		} catch (final Exception e) {

			e.printStackTrace();
		}
	}
	
	public JqueryZTreeNode getOther(){
		JqueryZTreeNode jzt=new JqueryZTreeNode();
		jzt.setIsParent("0");
		jzt.setId("99999");
		jzt.setName("调离");
		JqueryZTreeNode jzt1=new JqueryZTreeNode();
		jzt1.setIsParent("99999");
		jzt1.setId("99999");
		jzt1.setName("调离");
		List<JqueryZTreeNode> list=new ArrayList<JqueryZTreeNode>();
		list.add(jzt1);
		jzt.setChilds(list);
		return jzt;
	}
	

	/**
	 * 取部门树数据
	 * 
	 * @return
	 */
	public String getDeptTree() {

		String type = "";

		final UserInfo userinfo = (UserInfo) super.getRequest().getSession()
				.getAttribute(SystemUtil.USERINFO);
		if (userinfo != null) {
			System.out.println("=======" + userinfo.getRole().getName()+",,"+userinfo.getRole().getId());
			System.out.println("===InterfaceIpData.compid===" + InterfaceIpData.compid);
			/*
			 * "1""超级管理员" "2" "系统管理员" "3""部门管理员" "4""操作员"
			 */
			
			if (userinfo.getRole() != null
					&& (userinfo.getRole().getId() == 1 || userinfo.getRole()
							.getId() == 2)) {
			
			// deptList.add("所有部门");
				final DetachedCriteria dt = DetachedCriteria
						.forClass(Compdept.class);
				dt.add(Restrictions.eq("company.id",InterfaceIpData.compid));
				dt.addOrder(Order.asc("sortmanager"));
				deptList = this.compdeptService.findByCriteria(dt);
				type = "1";
			} else {

				final DetachedCriteria dt = DetachedCriteria
						.forClass(DeptAccount.class);
				
				dt.createAlias("compdept", "c");  
				dt.add(Restrictions.eq("c.company.id",InterfaceIpData.compid));
				dt.addOrder(Order.asc("c.sortmanager"));
				dt.add(Restrictions.eq("userid",
						Integer.valueOf(userinfo.getId().toString())));
				deptList = compdeptService.findByCriteria(dt);
				type = "2";
			}

		}
		
		// List<Compdept> list=this.compdeptService.getAllList();
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < deptList.size(); i++) {
			if (type.equals("2")) {
				final DeptAccount depa = (DeptAccount) deptList.get(i);
				final Compdept dept = depa.getCompdept();

				sb.append("{");
				sb.append("id:" + dept.getId());
				sb.append(",pId:" + dept.getPid());
				sb.append(",name:\"" + dept.getDeptname() + "\"");
				if (dept.getPid().equals("0")) {
					sb.append(",open:true");
				}
				sb.append("}");
				if (i != deptList.size() - 1) {
					sb.append(",");
				}
			} else {

				final Compdept dept = (Compdept) deptList.get(i);

				sb.append("{");
				sb.append("id:" + dept.getId());
				sb.append(",pId:" + dept.getPid());
				sb.append(",name:\"" + dept.getDeptname() + "\"");
				if (dept.getPid().equals("0")) {
					sb.append(",open:true");
				}
				sb.append("}");
				if (i != deptList.size() - 1) {
					sb.append(",");
				}
			}
			if(i==deptList.size()-1){
				sb.append(",{");
				sb.append("id:99999");
				sb.append(",pId:0");
				sb.append(",name:\"调离\"");
				sb.append("}");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}

	/**
	 * 
	 * @return
	 */
	public String userInfo() {

		try {

			final UserInfo userInfo = userInfoService.get(id);
			return ajax(JsonUtil.beanToJson(userInfo));
		} catch (final Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
   public void deptidsPut(){
	   this.setSession("deptidsKey", deptid+"");
//	   this.setSession("deptidsKey", deptids);
	    ajax("true");
   }

	/**
	 * 列表页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() {
		
		 if(!StringUtils.hasText(deptids)){
			 deptids= (String) this.getSession("deptidsKey");
		 }
		 
		try {
			final UserInfo userinfo = (UserInfo) super.getRequest()
					.getSession().getAttribute(SystemUtil.USERINFO);
			if (userinfo != null) {

				szUrDate();

				/*
				 * "1""超级管理员" "2" "系统管理员" "3""部门管理员" "4""操作员"
				 */
				if (userinfo.getRole() != null
						&& (userinfo.getRole().getId() == 1 || userinfo
								.getRole().getId() == 2)) {

				}

				// String areaCode =
				// super.getRequest().getParameter("areaCode");
				final HashMap<String, Object> searchMap = new HashMap<String, Object>();
				if (deptids != null) {
					searchMap.put("deptids", deptids);
				}
				if (pageSize > 0) {
					pager.setPageSize(pageSize);
				}
				if (utype != null) {
					if (utype == 0) {
						searchMap.put("user_type", utype);
					} else if (utype == 1) {
						searchMap.put("user_type", utype);
					} else if (utype == 3) {
						searchMap.put("forbidden", 1);
					}

				}
				if (StringUtils.hasText(uname)) {
					searchMap.put("name", uname);
				}
				
				searchMap.put("updatetype", "1,2");
				// pager.setSearchMap(searchMap);

				pager = deptuserService.findPagerByAccount(pager, searchMap);

				
				final ServletContext sc = ServletActionContext.getServletContext();
				final HashMap userCodeMap = (HashMap) sc.getAttribute("userCodeMap");
				if (userCodeMap != null && userCodeMap.size() > 0) {
					final List<Deptuser> list = (List<Deptuser>) pager.getResult();
					for (final Deptuser deptuser : list) {
						if (userCodeMap.get("U" + deptuser.getUserid()) != null) {
							deptuser.setLxrTxt("常用联系人");
						}
					}
					pager.setResult(list);
				}
					
			}

		} catch (final Exception e) {
			e.printStackTrace();
		}
		return "list";
	}

	public int getPageSize() {
		return pageSize;
	}

	/****
	 * 保存
	 */
	public String save() {

		try {

			final HttpServletResponse response = ServletActionContext
					.getResponse();
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			final String userCode = super.getRequest().getParameter("userCode");
			final String uname = super.getRequest().getParameter("uname");
			final String sex = super.getRequest().getParameter("sex");
			final String user_type = super.getRequest().getParameter(
					"user_type");
			final String phone = super.getRequest().getParameter("phone");
			final String birth = super.getRequest().getParameter("birth");
			
			final String email = super.getRequest().getParameter("email");
			final String fax = super.getRequest().getParameter("fax");
			final String local = super.getRequest().getParameter("local");
			final String hometel = super.getRequest().getParameter("hometel");
			final String emergencyphone = super.getRequest().getParameter("emergencyphone");
			final String address = super.getRequest().getParameter("address");
		
			Date updatetime = userInfoService.getUpdateTime("user");
			if (deptid == null) {
				response.getWriter().write("请选择部门!");
				return null;
			}

			final DetachedCriteria dt = DetachedCriteria
					.forClass(UserInfo.class);
			dt.add(Restrictions.eq("userCode", userCode));
			final List<UserInfo> userlist = compdeptService.findByCriteria(dt);
			if (userlist != null && userlist.size() > 0) {

				response.getWriter().write("账号已存在请重新输入!");
				return null;
			}

			final UserInfo user = new UserInfo();
			user.setUser_type(Integer.valueOf(user_type));
			user.setSex(Integer.valueOf(sex));
			user.setName(uname);
			user.setUserCode(userCode);
			user.setPhone(phone);
			user.setRole(null);
			if (StringUtils.hasText(birth)) {
				final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				final Date date = sdf.parse(birth);
				user.setBirth(date);
			} else {
				user.setBirth(new Date());
			}
			user.setForbidden(0);// 1表示禁用 0启用
			user.setUpdate_time(new Date());
			user.setEntrydate(new Date());
			user.setEmail(email);
			user.setFax(fax);
			user.setHometel(hometel);
			user.setLocal(local);
			user.setEmergencyphone(emergencyphone);
			user.setAddress(address);
			user.setCompid(5);
			
			
			userInfoService.save(user);
			Long modfiytime = updatetime.getTime() / 1000;
			byte[] by = new byte[14];
		    System.arraycopy(Formatu.int2byte(user.getId().intValue()), 0, by,0, 4); /*操作用户 */
			System.arraycopy(Formatu.int2byte(user.getCompid()), 0, by,4, 4); /*企业id  */
			System.arraycopy(Formatu.int2byte(modfiytime.intValue()), 0, by,8, 4); /*时间 */
			 short opertype=2;
			System.arraycopy(Formatu.short2byte(opertype), 0, by,12, 2); /*操作类型 */
	
			compdeptService.sendMsg(by, 1005);
			

			if (user != null && user.getId() > 0) {

				final Deptuser deptuser = new Deptuser();
				updatetime = userInfoService.getUpdateTime("deptuser");
				Compdept dept=new Compdept();
				dept.setId(5);
				deptuser.setUserid(Integer.valueOf(user.getId().toString()));
				deptuser.setDeptid(deptid);
				//
				deptuser.setAreaid(0);
				deptuser.setProid(0);
				deptuser.setRankid(0);
				deptuser.setUpdateTime(new Date());
				deptuser.setUpdatetype(1);//更新类型 1、新增 2、修改 3、删除
				deptuser.setUsersort(0);
				deptuser.setDept(dept);
				// //deptuser.setUserInfo(user);
				deptuserService.save(deptuser);
				modfiytime = updatetime.getTime() / 1000;
				by = new byte[18];
			    System.arraycopy(Formatu.int2byte(dept.getId()), 0, by,0, 4); /*操作用户 */
				System.arraycopy(Formatu.int2byte(deptuser.getUserid()), 0, by,4, 4); /*企业id  */
				System.arraycopy(Formatu.int2byte(deptid), 0, by,8, 4); /*时间 */
				System.arraycopy(Formatu.int2byte(modfiytime.intValue()), 0, by,12, 4); /*时间 */
				opertype=1;
				System.arraycopy(Formatu.short2byte(opertype), 0, by,16, 2); /*操作类型 */
				
				compdeptService.sendMsg(by, 1006);
				response.getWriter().write("true");
			}

		} catch (final Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/****
	 * 修改
	 */
	public String update() {

		try {

			final HttpServletResponse response = ServletActionContext
					.getResponse();
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			final String userCode = super.getRequest().getParameter("userCode");
			final String uname = super.getRequest().getParameter("name");
			final String sex = super.getRequest().getParameter("sex");
			final String user_type = super.getRequest().getParameter("user_type");
			final String phone = super.getRequest().getParameter("phone");
			final String birth = super.getRequest().getParameter("birth");
			
			final String email = super.getRequest().getParameter("email");
			final String fax = super.getRequest().getParameter("fax");
			final String local = super.getRequest().getParameter("local");
			final String hometel = super.getRequest().getParameter("hometel");
			final String emergencyphone = super.getRequest().getParameter("emergencyphone");
			final String address = super.getRequest().getParameter("address");

			final UserInfo userInfo = userInfoService.get(id);
			if (userInfo != null) {

				if (!userCode.equals(userInfo.getUserCode())) {
					final DetachedCriteria dt = DetachedCriteria
							.forClass(UserInfo.class);
					dt.add(Restrictions.eq("userCode", userCode));
					final List<UserInfo> userlist = compdeptService
							.findByCriteria(dt);
					if (userlist != null && userlist.size() > 0) {

						response.getWriter().write("账号已存在请重新输入!");
						return null;
					}
				}
				Date updatetime = userInfoService.getUpdateTime("user");
				userInfo.setUserCode(userCode);
				userInfo.setName(uname);
				userInfo.setSex(Integer.valueOf(sex));
				userInfo.setUser_type(Integer.valueOf(user_type));
				userInfo.setPhone(phone);
				if (StringUtils.hasText(birth)) {
					final SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyy-MM-dd");
					final Date date = sdf.parse(birth);
					userInfo.setBirth(date);
				}
				userInfo.setUpdatetype(2);//更新类型 1、新增 2、修改 3、删除
				userInfo.setUpdate_time(new Date());
				userInfo.setEmail(email);
				userInfo.setFax(fax);
				userInfo.setHometel(hometel);
				userInfo.setLocal(local);
				userInfo.setEmergencyphone(emergencyphone);
				userInfo.setAddress(address);
				userInfoService.update(userInfo);
				Long modfiytime = updatetime.getTime() / 1000;
				byte[] by = new byte[14];
			    System.arraycopy(Formatu.int2byte(userInfo.getId().intValue()), 0, by,0, 4); /*操作用户 */
				System.arraycopy(Formatu.int2byte(userInfo.getCompid()), 0, by,4, 4); /*企业id  */
				System.arraycopy(Formatu.int2byte(modfiytime.intValue()), 0, by,8, 4); /*时间 */
				short opertype=2;
				System.arraycopy(Formatu.short2byte(opertype), 0, by,12, 2); /*操作类型 */
				compdeptService.sendMsg(by, 1005);
				response.getWriter().write("修改成功!");
				return null;
			}

		} catch (final Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/****
	 * 修改用户状态
	 */
	public String updateState() {

		try {

			final UserInfo userInfo = userInfoService.get(id);
			Date updatetime = userInfoService.getUpdateTime("user");
			if (userInfo != null && utype != null) {

				if (utype == 0) {
					userInfo.setForbidden(1);
					userInfo.setUpdatetype(2);//更新类型 1、新增 2、修改 3、删除
					userInfo.setUpdate_time(new Date());
					userInfoService.update(userInfo);
				} else if (utype == 1) {
					userInfo.setForbidden(0);
					userInfo.setUpdatetype(2);//更新类型 1、新增 2、修改 3、删除
					userInfo.setUpdate_time(new Date());
					userInfoService.update(userInfo);
					
				}
				Long modfiytime = updatetime.getTime() / 1000;
				byte[] by = new byte[14];
			    System.arraycopy(Formatu.int2byte(userInfo.getId().intValue()), 0, by,0, 4); /*操作用户 */
				System.arraycopy(Formatu.int2byte(userInfo.getCompid()), 0, by,4, 4); /*企业id  */
				System.arraycopy(Formatu.int2byte(modfiytime.intValue()), 0, by,8, 4); /*时间 */
				short opertype=2;
				System.arraycopy(Formatu.short2byte(opertype), 0, by,12, 2); /*操作类型 */
				compdeptService.sendMsg(by, 1005);
				if (utype == 0) {
					return ajax("禁用成功!");
				} else if (utype == 1) {
					
					return ajax("启用成功!");
				}
				
			}

		} catch (final Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	/****
	 * 设置常用联系人
	 * 
	 * @return
	 */
	public String updateLxr() {

		try {
			szUrDate();
			final DetachedCriteria dt = DetachedCriteria
					.forClass(UserRoamingdata.class);
			dt.add(Restrictions.eq("userid", 0));
			final List<UserRoamingdata> userlist = compdeptService
					.findByCriteria(dt);
			if (userlist != null && userlist.size() > 0) {

				final UserRoamingdata userRoamingdata = userlist.get(0);

				final ServletContext sc = ServletActionContext
						.getServletContext();
				final HashMap userCodeMap = (HashMap) sc
						.getAttribute("userCodeMap");

				if (id != null) {

					final Object obj = userCodeMap.get("U" + id);
					if (obj != null) {
						userCodeMap.remove("U" + id);
					} else {
						userCodeMap.put("U" + id, id);
					}
					// 更新数据
					String str = "";
					if (userCodeMap.size() > 0) {
						final Iterator iterator = userCodeMap.keySet()
								.iterator();
						int i = 0;
						while (iterator.hasNext()) {
							i++;
							final Object key = iterator.next();
							final Object val = userCodeMap.get(key);
							if (i == userCodeMap.size()) {
								str += val + ";";
							} else {
								str += val + "|";
							}
						}
					}
					userRoamingdata.setContent(str);
					Long time = System.currentTimeMillis()/1000;
					userRoamingdata.setUpdatetime(time);
					userRoamingdataService.update(userRoamingdata);
				}

				return ajax("设置成功!");
			}

		} catch (final Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	public void szUrDate() {

		/*
		 * ServletContext sc = ServletActionContext.getServletContext();
		 * if(sc.getAttribute("userCodeMap")==null)
		 */
		 HashMap userCodeMap = new HashMap();
		 DetachedCriteria dt = DetachedCriteria
				.forClass(UserRoamingdata.class);
		dt.add(Restrictions.eq("userid", 0));
		 List<UserRoamingdata> userlist = compdeptService
				.findByCriteria(dt);
		if (userlist != null && userlist.size() > 0) {

			 UserRoamingdata userRoamingdata = userlist.get(0);
			String ur = userRoamingdata.getContent();
			ur = ur.replaceAll(";", "");
			if (StringUtils.hasText(ur)) {
				 String[] userRoam = ur.split("\\|");
				for (int i = 0; i < userRoam.length; i++) {
					 String str = userRoam[i];
					userCodeMap.put("U" + str, str);
				}
			}
			 ServletContext sc = ServletActionContext.getServletContext();
			 java.util.HashMap verifyCodeMap = (sc
					.getAttribute("verifyCodeMap") == null ? new HashMap()
					: (HashMap) sc.getAttribute("verifyCodeMap"));
			sc.setAttribute("userCodeMap", userCodeMap);

		} else {

			 UserRoamingdata userRoamingdata = new UserRoamingdata();
			userRoamingdata.setUserid(0);
			userRoamingdata.setContenttype("1");// '漫游数据类型
												// 1：常用联系人，2：常用部门，3：关注人',
			Long time = System.currentTimeMillis()/1000;
			userRoamingdata.setUpdatetime(time);
			userRoamingdata.setContent(";");
			this.userRoamingdataService.save(userRoamingdata);
			 ServletContext sc = ServletActionContext.getServletContext();
			 java.util.HashMap verifyCodeMap = (sc
					.getAttribute("verifyCodeMap") == null ? new HashMap()
					: (HashMap) sc.getAttribute("verifyCodeMap"));
		}

	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public String getNode() {
		return node;
	}

	public void setNode(String node) {
		this.node = node;
	}

	public Integer getPid() {
		return pid;
	}

	public void setPid(Integer pid) {
		this.pid = pid;
	}

	public CompdeptService getCompdeptService() {
		return compdeptService;
	}

	public void setCompdeptService(CompdeptService compdeptService) {
		this.compdeptService = compdeptService;
	}

	public Integer getDeptid() {
		return deptid;
	}

	public void setDeptid(Integer deptid) {
		this.deptid = deptid;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public Integer getUtype() {
		return utype;
	}

	public void setUtype(Integer utype) {
		this.utype = utype;
	}

	public List getDeptList() {
		return deptList;
	}

	public void setDeptList(List deptList) {
		this.deptList = deptList;
	}

	public String getDeptids() {
		return deptids;
	}

	public void setDeptids(String deptids) {
		this.deptids = deptids;
	}

}
